<template>
  <el-form-item :label="label" :prop="prop">
    <el-upload
      action=""
      list-type="picture-card"
      :accept="acceptFile"
      :multiple="multiple"
      :limit="limitNum"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpdata"
      :on-change="handleChange"
      :file-list="uploadFileList"
      :on-remove="Remove"
      :class="{ hide: uploadFileList.length > 0 }"
      :disabled="disabled"
    >
      <template #default>
        <el-icon class="upload_icon">
          <plus />
        </el-icon>
      </template>
      <template #file="{ file }">
        <div>
          <el-image style="el-upload-list__item-actions" :src="file.url"> </el-image>
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon><delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
      <template #tip>
        <div class="el-upload__tip">
          <!-- <span
            >单张图片大小不超过10M，支持png；jpg；jpeg格式，图片宽度不超过1440px,高度不超过1080px</span
          > -->
        </div>
      </template>
    </el-upload>
  </el-form-item>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script setup lang="ts">
  import { ref, reactive, defineProps, onUnmounted, watch } from 'vue'
  import { ElForm, ElMessage } from 'element-plus'
  import { Plus, ZoomIn, Download, Delete, TurnOff } from '@element-plus/icons-vue'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import { uploadFile, uploadOss, uploadFile2 } from '@/api/common'
  import { IsNotEmpty, getSetionId, getImageMaxWH, getImage_wh } from '@/utils/utils'
  import bus from '@/utils/bus'
  const emit = defineEmits(['submit'])

  const formRef = ref<InstanceType<typeof ElForm>>()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  // const disabled = ref(false);
  const hideUpload = ref(false)
  var uploadFileList = ref([])
  const isEdit = ref(false) // 是否为编辑

  const props = defineProps<{
    upInfo: {
      type: number //文件类型
      label: string //文件名称
      prop: string // 是否是必传
      files: any //文件
      multiple: {
        //是否支持多选
        type: boolean
        default: false
      }
      limitSize: number // 最大文件上传限制
      limitNum: {
        // 上最大传数量
        type: number
        default: 1
      }
      acceptFile: string // 上传类型文件判断
      disabled: {
        // 是否禁用
        type: boolean
        default: false
      }
    }
    image: {
      type: string
      default: undefined
    }
  }>()
  const { type, label, prop, files, multiple, limitSize, acceptFile, limitNum, uploadName, disabled } = props.upInfo
  const beforeUpdata = async (file: any) => {
    const is2M = file.size / 1024 / 1024 <= limitSize
    const { W, H } = await getImage_wh(file)
    if (W > 1440) {
      ElMessage.warning(`上传图片尺寸最大宽度1440px`)
      handleRemove(file)
      return
    }
    if (H > 1080) {
      ElMessage.warning(`上传图片尺寸最大高度1080px`)
      handleRemove(file)
      return
    }
    if (!is2M) {
      ElMessage.warning(`上传的图片最大支持${limitSize}M`)
      handleRemove(file)
      return
    }
    return is2M && W <= 1440 && H <= 1080
  }
  const handleRemove = (file: UploadFile) => {
    console.log('删除--', file, uploadFileList.value)
    
    uploadFileList.value = uploadFileList.value.filter((item: any) => IsNotEmpty(uploadFileList.value))
    uploadFileList.value = uploadFileList.value.filter((item: any) => item.url != file.url)
    emit('submit', uploadFileList.value)
  }
  const Remove = (file: UploadFile, list: UploadFile[]) => {
    uploadFileList.value = list
    emit('submit', list)
    bus.emit('empty')
    console.log(file, list, '===自动删除')
  }
  // 上传文件
  const uploadImg = async (file: any) => {
    file = file.raw
    let flag = await beforeUpdata(file)
    if (!flag) return
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  // 长传改变
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    let existFile = list.slice(0, list.length - 1).find((f) => f.name === file.name)
    if (existFile) {
      ElMessage.error('当前文件已经存在!')
      list.pop()
      return
    }
    const data: any = await uploadImg(file)
    uploadFileList.value.push(data)

    hideUpload.value = uploadFileList.value.length >= limitNum
    // hideUpload.value = uploadFileList.value.length >= 1
    emit('submit', uploadFileList.value)
  }
  const handleExceed = (file: UploadFile, list: UploadFile[]) => {
    ElMessage.warning(`当前限制选择 ${limitNum} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + list.length} 个文件`)
    Remove(file, list)
  }
  // 图片数据回显
  const echo = (url: any) => {
    console.log('回显', url)
    if (url) {
      uploadFileList.value.push({ url })
    }
  }
  watch(
    () => props.upInfo.files,
    (val: any) => {
      console.log(val)
      if (val == [] || val[0]?.url == '' || val[0]?.url == null) {
        uploadFileList.value = []
      } else {
        uploadFileList.value = val
      }
    }
  )
  // 清空数据回显
  const empty = () => {
    uploadFileList.value = []
    console.log(111)
    return
  }
  // 编辑状态时只能上传一张照片
  const singleImg = (res: boolean) => {
    hideUpload.value = res
    isEdit.value = res
  }
  //上传图片的弹框
  const upPic = () => {
    isEdit.value = false
  }
  bus.on('upPic', upPic)
  // watch(
  //   () => prop.image,
  //   (nVal: any, oVal: any) => {
  //     console.log(nVal, oVal, '===watch')
  //     uploadFileList.value.push(nVal)
  //   },
  //   { immediate: true }
  // )
  // 主动暴露方法
  defineExpose({ empty, echo, singleImg, upPic, beforeUpdata })
  const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
    console.log(dialogImageUrl.value, '----file预览')
  }
  // 下载
  const handleDownload = (file: UploadFile) => {
    console.log(file)
  }
  onUnmounted(() => {
    bus.off('upPic', upPic)
  })
</script>
<style lang="scss" scoped>
  .pre_img_box {
    overflow: hidden;
    .pre_image {
      display: block;
      margin: auto;
      max-height: 400px;
    }
  }
</style>
<style>
  .hide .el-upload--picture-card {
    display: none;
  }
  .upload_icon {
    width: 140px;
    height: 90px;
  }
</style>
